package org.example.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.example.common.BaseContext;
import org.example.common.R;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* 检查用户是否已经完成登录
 **/
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符请求
    public static final AntPathMatcher PATH_MATCHER =new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String requestURI=request.getRequestURI();
        String[] Urls=new String[]{
          "/employee/login",
          "/employee/logout",
          "/common/**",
          "/backend/**", "/front/**","/user/login","/user/sendMsg"
        };

        if(check(Urls,requestURI)){
            log.info(requestURI+"请求，不用拦截");
            filterChain.doFilter(request,response);
            return;
        }
        //判断登录状态
        Object employee = request.getSession().getAttribute("employee");
        if (employee!=null){

            BaseContext.setCurrentId((Long) employee);
            filterChain.doFilter(request,response);
            return;
        }


        Object user = request.getSession().getAttribute("user");
        if (user!=null){

            BaseContext.setCurrentId((Long) user);
            filterChain.doFilter(request,response);
            return;
        }
        //未登录,通过输出流向客户端返回数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("拦截到请求：{}",requestURI);
    }

    public boolean check(String urls[],String requestURI){
        for (String url:urls) {
            if(PATH_MATCHER.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
